<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 前台会员地址操作ajax
 * @package  ajax/shop/default
 * @author   allen.qiang
 */

quanli_require('module/base/customer/custDeliver.class.php');

class ajax_deliver {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && quanli_is_int($_REQUEST['operFlg'])) {

            switch($_REQUEST['operFlg']) {

                case 2: //新增、修改地址
                    $this->deliverEdit();
                    break;

                case 3: //删除会员收获地址
                    $this->deliverDelete();
                    break;

                case 4: //根据地址获取配送方式
                    $this->getSendByAddress();
                    break;

                case 5: //设置默认地址
                    $this->set_default();
                    break;

                case 6: //测试接口，根据地址获取配送方式及运费
                    $this->getSendByAddress1();
                    break;

                default:
                    returnJsonData('参数错误');
                    break;

            }

        } else {

            returnJsonData('参数错误');

        }

    }

    private function deliverEdit() {

        global $G_SHOP;

        if(!$G_SHOP->currentPCustID){
            returnJsonData('请先登录');
        }

        //地址类型，type为2的时候为自提
        if(isset($_REQUEST['type']) && $_REQUEST['type'] == 2){

            //验证配送站参数
            if(!isset($_REQUEST['distribution_id']) || empty($_REQUEST['distribution_id'])){
                returnJsonData('自提网店必须选择');
            }

            $distribution_id = $_REQUEST['distribution_id'];

            //包含配送站类
            quanli_require('module/base/system/sysDistribution.class.php');

            //实例化配送站类
            $sysDistribution = new sysDistribution();

            //查询配送站信息
            $arg_array = array(
                'distribution_id' => $distribution_id
            );

            $distribution_array = $sysDistribution->search( $arg_array );

            $_REQUEST['provinceid'] = $distribution_array[0]['provinceid'];
            $_REQUEST['cityid'] = $distribution_array[0]['cityid'];
            $_REQUEST['countyid'] = $distribution_array[0]['countyid'];
            $_REQUEST['address'] = $distribution_array[0]['address'];

        }

        //实例化会员类
        $custDeliver = new custDeliver();

        //保存地址信息
        $_REQUEST['creator'] = $G_SHOP->currentCustomerID;
        $_REQUEST['pcustID'] = $G_SHOP->currentPCustID;
        $result_array = $custDeliver->editCustDeliver( $_REQUEST, true );
        if ($result_array['code'] != 200) {
            returnJsonData( $result_array['message'], $result_array['code'] );
        }

        $data_array =& $result_array['data'];

        //根据用户登录状态显示
        if( in_array($G_SHOP->isGuest, array(1, 2)) ){
            $address_last = mb_substr($data_array['address'], -1, 1, 'utf-8');
            $address_first = mb_substr($data_array['address'],  0, 1, 'utf-8');
            $mobile_first = mb_substr($data_array['mobile'], 0, 1, 'utf-8');
            $mobile_last = mb_substr($data_array['mobile'], -1, 1, 'utf-8');
            $data_array['address'] = $address_first.'********'.$address_last;
            $data_array['custName'] = '***';
            $data_array['mobile'] = $mobile_first.'********'.$mobile_last;
        }

        returnJsonData( $result_array['message'], $result_array['code'], $result_array['data'] );

    }

    /**
     * 删除收货地址
     */
    private function deliverDelete() {

        global $G_SHOP;

        if(!$G_SHOP->currentPCustID){
            returnJsonData('请先登录');
        }

        if (!isset($_REQUEST['id']) || !is_numeric($_REQUEST['id']))
            returnJsonData('参数错误');

        //实例会员地址类
        $custDeliver = new custDeliver( $G_SHOP->DBCA );

        //删除会员收货地址
        $result_array = $custDeliver->delCustDeliver($G_SHOP->currentPCustID, $_REQUEST['id']);

        echo json_encode( $result_array );

    }

    /**
     * 根据地址获取配送方式
     */
    private function getSendByAddress(){

        if(!isset($_REQUEST['provinceid'], $_REQUEST['cityid'], $_REQUEST['countyid'], $_REQUEST['address'])){
            returnJsonData('缺少参数');
        }

        global $G_SHOP;
        quanli_require('module/base/bill/billCheckout.class.php');
        quanli_require('module/base/system/sysSend.class.php');

        //实例订单结算类
        $billCheckout = new billCheckout( $G_SHOP->DBCA );

        //实例化配送方式类
        $sysSend = new sysSend();

        try{

            $province_obj = new entity('sys_region');
            $province_obj->id = $_REQUEST['provinceid'];
            $province_obj->region_level = 1;
            if (!$G_SHOP->DBCA->fetch($province_obj))
                throw new Exception('省份信息没有找到', 404);

            //查询市区信息
            $city_obj = new entity('sys_region');
            $city_obj->id = $_REQUEST['cityid'];
            $city_obj->region_level = 2;
            $G_SHOP->DBCA->fetch($city_obj);

            $county_obj = new entity('sys_region');
            $county_obj->id = $_REQUEST['countyid'];
            $county_obj->region_level = 3;
            $G_SHOP->DBCA->fetch($county_obj);

            //根据地址匹配经纬度
            $address_detail = $province_obj->name . $city_obj->name . $county_obj->name . $_REQUEST['address'];
            //add allen.qiang 20141210 FUN-BK-0041-G7地址库平台接入---start
            if(G_LATITUDE_COUNTY==0){ //地址经纬度不开启区匹配
                $address_detail = $province_obj->name.$city_obj->name.$_REQUEST['address'];
            }
            //add allen.qiang 20141210 FUN-BK-0041-G7地址库平台接入---end
            $coordinate_array = get_address_coordinate( $address_detail );
            if ($coordinate_array['match'] == 0) {
                throw new Exception('收货地址无法匹配,请重新输入', 404);
            }

            //add allen.qiang 20141202 详细地址是否在当前城市站判断---start
            $city_array = $G_SHOP->getCache('city');                                        //读取缓存城市数据
            foreach($city_array as &$city_check) {
                if($city_check["name"] != $city_obj->name && $city_check["front_display"]==1){
                    $check_city=array();
                    $check_city[]=$city_check["name"];
                    $check_city[]=mb_substr($city_check["name"], 0, 2, 'utf-8');
                    if(in_array(mb_substr($_REQUEST['address'], 0, 2, 'utf-8'), $check_city) || in_array(mb_substr($_REQUEST['address'], 0, 3, 'utf-8'), $check_city))
                        throw new Exception('地址不在'.mb_substr($city_obj->name, 0, 2, 'utf-8').'，请重新选择，或切换至'.mb_substr($city_check["name"], 0, 2, 'utf-8').'站重新下单', 404);
                }
            }
            //add allen.qiang 20141202 详细地址是否在当前城市站判断---end

//del allen.qiang 20141202 详细地址是否在当前城市站判断---start
            //详细地址是否在当前城市站判断
          /*  $check_sh = array('上海', '上海市');
            $check_hz = array('杭州', '杭州市');

            if(in_array($city_obj->name, $check_sh)){
                if(in_array(mb_substr($_REQUEST['address'], 0, 2, 'utf-8'), $check_hz) || in_array(mb_substr($_REQUEST['address'], 0, 3, 'utf-8'), $check_hz))
                    throw new Exception('地址不在上海，请重新选择，或切换至杭州站重新下单', 404);

            }elseif(in_array($city_obj->name, $check_hz)){
                if(in_array(mb_substr($_REQUEST['address'], 0, 2), $check_sh, 'utf-8') || in_array(mb_substr($_REQUEST['address'], 0, 3, 'utf-8'), $check_sh))
                    throw new Exception('地址不在杭州，请重新选择，或切换至上海站重新下单', 404);
            }*/
//del allen.qiang 20141202 详细地址是否在当前城市站判断---start

            //得到地图区域
            $result_array = $billCheckout->getMapArea( $coordinate_array['longitude'], $coordinate_array['latitude'], $_REQUEST['cityid'], 2);

            $areaID = $result_array['areaID'];
            if ($areaID == 0) {
                throw new Exception('超出配送范围，请重新选择地址，或选择自提点自提', 404);
            }

            //查询地图区域下的所有配送区域
            $arg_array = array(
                'areaID' => $areaID
            );
            $send_area_array = $sysSend->searchSendArea( $arg_array );
            if (!$send_area_array) {
                return null;
            }

            $return_array = array();

            $sendFlg = 0;
            foreach($send_area_array as &$send) {

                //根据配送区域查询配送方式
                $arg_array = array(
                    'sendTypeID' => $send['sendTypeID']
                );

                $sendType_array = $sysSend->searchSendType( $arg_array );
                if(!$sendType_array)
                    continue;

                if($sendFlg == 0){
                    $sendFlg++;
                    $return_array = array(
                        'freight' => $send['freight'],
                        'overweight_freight' => $send['overweight_freight'],
                        'send_region_id' => $send['send_region_id'],
                        'send_region_name' => $send['send_region_name'],
                        //add allen.qiang 2015-03-04 MK-FUN-AC-45-WAP端迷你拿破仑活动---start
                        'areaID'=> $send['areaID']
                        //add allen.qiang 2015-03-04 MK-FUN-AC-45-WAP端迷你拿破仑活动---end
                    );
                }
            }
            error_log(print_r($return_array,1));
            returnJsonData('ok', 200, $return_array);

        }catch (Exception $e) {

            if ($e->getCode() > 0)
                returnJsonData($e->getMessage(),$e->getCode() );
            else {
                error_log($e->getMessage());
                returnJsonData('系统错误', 500 );
            }

        }

    }

    /**
     * 设置默认地址
     */
    private function set_default(){

        global $G_SHOP;

        if(!$G_SHOP->currentPCustID){
            returnJsonData('请先登录');
        }

        if (!isset($_REQUEST['id']) || !is_numeric($_REQUEST['id']))
            returnJsonData('参数错误');

        try{

            $G_SHOP->DBCA->beginTransaction();

            $deliver_obj = new entity('cust_deliver');
            $deliver_obj->pcustID = $G_SHOP->currentPCustID;
            $deliver_obj->deliverID = $_REQUEST['id'];

            $G_SHOP->DBCA->stmt_query('UPDATE cust_deliver SET is_default = 0 WHERE pcustID=?', 'i',$deliver_obj->pcustID);

            if (!$G_SHOP->DBCA->fetch($deliver_obj))
                throw new Exception('没有找到此地址，请刷新重试', 404);


            $deliver_obj->is_default = 1;
            $G_SHOP->DBCA->save($deliver_obj);

            $G_SHOP->DBCA->commit();

            returnJsonData('ok', 200);

        }catch (Exception $e){

            $G_SHOP->DBCA->rollBack();

            if($e->getCode() > 0){
                returnJsonData($e->getMessage(), $e->getCode());
            }else{
                error_log($e->getMessage());
                returnJsonData('系统错误', 500);
            }

        }
    }

    /**
     * 根据地址获取配送方式及运费   测试用
     * add by allen.qiang 2015/11/23
     */
    private function getSendByAddress1(){
        returnJsonData('接口关闭');
        if(!isset($_REQUEST['address'])){
            returnJsonData('缺少参数');
        }

        global $G_SHOP;
        quanli_require('module/base/bill/billCheckout.class.php');
        quanli_require('module/base/system/sysSend.class.php');
        quanli_require('module/base/system/sysDistribution.class.php');

        $billCheckout = new billCheckout( $G_SHOP->DBCA );
        //实例化配送方式类
        $sysSend = new sysSend();

        $sysDistribution = new sysDistribution();

        try{

            //根据地址匹配经纬度
            $address_detail = $_REQUEST['address'];
            $coordinate_array = get_address_coordinate( $address_detail );
            if ($coordinate_array['match'] == 0) {
                throw new Exception('收货地址无法匹配,请重新输入', 404);
            }

            //得到地图区域
            $result_array = $billCheckout->getMapArea( $coordinate_array['longitude'], $coordinate_array['latitude'], 110, 2);

            $areaID = $result_array['areaID'];
            if ($areaID == 0) {
                throw new Exception('超出配送范围，请重新选择地址，或选择自提点自提', 404);
            }

            //查询地图区域下的所有配送区域
            $arg_array = array(
                'areaID' => $areaID
            );
            $send_area_array = $sysSend->searchSendArea( $arg_array );
            if (!$send_area_array) {
                return null;
            }

            $return_array = array();

            $sendFlg = 0;
            foreach($send_area_array as &$send) {

                //根据配送区域查询配送方式
                $arg_array = array(
                    'sendTypeID' => $send['sendTypeID']
                );

                $sendType_array = $sysSend->searchSendType( $arg_array );
                if(!$sendType_array)
                    continue;

                if($sendFlg == 0){
                    //得到配送站
                    $result_array2 = $billCheckout->getMapArea( $coordinate_array['longitude'], $coordinate_array['latitude'], 110, 1);
                    if($result_array2['areaID'] == 0)
                    {
                        return array('code'=>404,'message'=>'抱歉,该地址不在配送区域内!');
                    }

                    $arg_array = array(
                        'areaID' => $result_array2['areaID']
                    );
                    $sysDistribution_reslt = $sysDistribution->searchDistributionMapArea($arg_array);

                    $arg_array = array(
                        'distribution_id' => $sysDistribution_reslt[0]['distribution_id']
                    );

                    $sysDistribution_reslt = $sysDistribution->search($arg_array);
                    $sendFlg++;
                    $return_array = array(
                        'freight' => $send['freight'],
                        'overweight_freight' => $send['overweight_freight'],
                        'send_region_id' => $send['send_region_id'],
                        'send_region_name' => $send['send_region_name'],
                        'areaID'=> $send['areaID'],
                        'distribution_id'=> $sysDistribution_reslt[0]['distribution_id'],
                        'distribution_name'=> $sysDistribution_reslt[0]['distribution_name']
                    );
                }
            }


            returnJsonData('ok', 200, $return_array);

        }catch (Exception $e) {

            if ($e->getCode() > 0)
                returnJsonData($e->getMessage(),$e->getCode() );
            else {
                error_log($e->getMessage());
                returnJsonData('系统错误', 500 );
            }

        }

    }

}